package com.nancy.java_design.abstract_factory.demo2;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 简单工厂+配置文件解除耦合
 */
public class CoffeeFactory {
    //1.声明一个map集合
    public static final Map<String, Coffee> coffeeMap = new HashMap<>();

    //2.静态代码块，加载配置文件，初始化map集合
    static {
        //2.1 创建Propeties对象
        Properties properties = new Properties();
        //2.2 获取配置文件中的数据，并存储到map中
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("coffee.properties");
        try {
            properties.load(is);
            Set<Object> keys = properties.keySet();
            for (Object key : keys) {
                String className = properties.getProperty(key.toString());
                Class clazz = Class.forName(className);
                //创建对象
                Coffee coffee = (Coffee) clazz.newInstance();
                //存储到map中
                coffeeMap.put((String) key, coffee);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //3.提供一个获取咖啡的方法
    public static Coffee getCoffee(String name) {
        return coffeeMap.get(name);
    }

}
